﻿using Authentication.Core.Configuration;
using Authentication.Model.Interface;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Authentication.Response;
using Common.Contract.Paging;
using Common.Contract.SystemConfig.Record;
using Common.Data.Repository.Enum;
using Common.Service.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Authentication.Core.ServiceCommand.ChangeDao
{
    public class RetrieveChangeDaoCifByListCifServiceCommand : ProviderServiceCommand<IProviderFactory, RetrieveChangeDaoCifRequest, RetrieveChangeDaoCifResponse>
    {

        public int pageSize = 10, pageIndex = 0, totalRecord = 0;
        public string TextSearch;
        public int ChangeDaoRequestId;
        public List<ChangeDaoCifRecord> ListChangeCif;
        public UserRecord CurrentUser;
        public FilterRecord SearchColumns = null;
        public RetrieveChangeDaoCifByListCifServiceCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(RetrieveChangeDaoCifRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (Request.CurrentUser == null)
            {
                throw new ArgumentException("Dao must be set", "request");
            }
            else
            {
                CurrentUser = request.CurrentUser;
            }

            if (Request.ListCif == null || Request.ListCif.Count == 0)
            {
                throw new ArgumentException("ListCif must be set", "request");
            }
            else
            {
                ListChangeCif = request.ListCif;
            }

            SearchColumns = Request.Filter;
        }

        protected override bool OnExecute(RetrieveChangeDaoCifResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            int pageSize = 0, pageIndex = 0, totalRecord = 0;
            DateTime last6Month = DateTime.Now.AddMonths(-6);
            var applicationKey = Request.Header.ApplicationKey;
            try
            {
                if (Request.Page != null)
                {
                    pageIndex = Request.Page.PageIndex ?? 0;
                    pageSize = Request.Page.PageSize ?? 0;
                }
                List<string> listCif = ListChangeCif.Select(x => x.Cif).ToList();
                var listProduct = Providers.ChangeDao.RetrieveListChangeDaoProductByCif(ListChangeCif, CurrentUser);

                var listDao = Providers.Users.RetrieveAllUser().ToDictionary(x => x.Dao);
                var listCustomer = Providers.Customer.RetrieveListCustomerByCif(listCif).ToDictionary(x => x.Cif);

                if (listCustomer == null)
                {
                    response.ErrorMessage = string.Format("Can not found user with Dao={0}", CurrentUser.Dao);
                    response.IsSuccess = false;
                }
                List<ChangeDaoCifRecord> records = (from x in ListChangeCif
                                                    join y in listProduct on x.Cif equals y.Cif into y1
                                                    from y2 in y1.DefaultIfEmpty()
                                                    group y2 by x into yg
                                                    select new ChangeDaoCifRecord
                                                    {
                                                        Cif = yg.Key.Cif,
                                                        NewDao = string.Format("{0} (DAO: {1} - {2})", listDao[yg.Key.NewDao].DaoName, yg.Key.NewDao, listDao[yg.Key.NewDao].Position),
                                                        NewDaoName = yg.Key.NewDao,
                                                        CustomerName = listCustomer[yg.Key.Cif].CusName,
                                                        Segment = listCustomer[yg.Key.Cif].SubSegment,
                                                        LastUpdateData = listCustomer[yg.Key.Cif].LastUpdateDate,
                                                        IsApproved = yg.Key.IsApproved,
                                                        CheckCondition = new CheckChangeDaoConditionRecord
                                                        {
                                                            IsSameSegment = (listDao[yg.Key.NewDao].Position.Equals("SBO") && listCustomer[yg.Key.Cif].SubSegment.Equals("SME")) || (listDao[yg.Key.NewDao].Position.Equals("MBO") && !listCustomer[yg.Key.Cif].SubSegment.Equals("SME")) || (listDao[yg.Key.NewDao].GroupId.Equals("4") && !string.IsNullOrEmpty(listDao[yg.Key.NewDao].Team) && listCustomer[yg.Key.Cif].SubSegment.Equals("MSME")),
                                                            IsLast6MonthUpdate = listCustomer[yg.Key.Cif].LastUpdateDate.HasValue && listCustomer[yg.Key.Cif].LastUpdateDate > last6Month,
                                                            NeedApprove = !listCustomer[yg.Key.Cif].Dao.Equals(yg.Key.NewDao) && listCustomer[yg.Key.Cif].BranchId.Equals(CurrentUser.BranchId)
                                                        },
                                                        IsDisabled = !listCustomer[yg.Key.Cif].BranchId.Equals(CurrentUser.BranchId) && yg.Count() == 0,
                                                        ListChangeDaoProduct = (yg.FirstOrDefault() == null) ? new List<ChangeDaoProductCheckedRecord>() : yg.Select(y => new ChangeDaoProductCheckedRecord
                                                        {
                                                            Cif = y.Cif,
                                                            NoProduct = y.NoProduct,
                                                            TypeProduct = y.TypeProduct,
                                                            Dao = string.IsNullOrEmpty(y.Dao) ? string.Empty : listDao.ContainsKey(y.Dao) ? string.Format("{0} (DAO: {1} - {2})", listDao[y.Dao].DaoName, y.Dao, listDao[y.Dao].Position) : y.Dao,
                                                            DataDate = y.BusinessDate.ToString("dd/MM/yyyy"),
                                                            IsApproved = yg.Key.ListChangeDaoProduct != null && yg.Key.ListChangeDaoProduct.Any(x => x.NoProduct.Equals(y.NoProduct)) ? yg.Key.ListChangeDaoProduct.Single(x => x.NoProduct.Equals(y.NoProduct)).IsApproved : true,
                                                            NeedApprove = string.IsNullOrEmpty(y.Dao) ? true : !y.Dao.Equals(yg.Key.NewDao)
                                                        }).ToList()
                                                    }).ToList();

                response.Records = records;
                response.Page = new PageRecord
                {
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    TotalRecords = totalRecord,
                };
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
                response.ErrorMessage = string.Format("Can not found user with Dao={0}", CurrentUser.Dao);
                response.IsSuccess = false;
            }
            return isSuccess;
        }
    }
}
